package com.ptp.backendcertms.networksecurity.filter.form;

import com.ptp.backendcertms.networksecurity.filter.BaseFilter;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ptp.backendcertms.api.internal.constant.CertMsConstant.*;

/**
 * B端表单过滤器（针对文件上传相关接口）
 *
 * @author songcongcong
 * @date 2022/6/13
 */
@Slf4j
public class FormRequestFilter extends BaseFilter implements Filter {
    /**
     * 做处理的url，进行处理
     */
    private List<String> includedUrls;

    @Override
    public void init(FilterConfig filterConfig) {
        includedUrls = getIncludeOrExcludeUrls(filterConfig, INCLUDED_URLS);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        if (log.isDebugEnabled()) {
            log.debug("formRequest Filter is open");
        }
        HttpServletRequest req = (HttpServletRequest) request;
        // 不做处理的url
        if (!servletPathIsMatching(includedUrls, req.getServletPath())) {
            filterChain.doFilter(req, response);
            return;
        }
        // 请求参集合
        Map<String, String[]> summaryInfoMap = new HashMap<>(128);
        summaryInfoMap.putAll(req.getParameterMap());
        ParameterRequestWrapper parameterRequestWrapper = new ParameterRequestWrapper(req, summaryInfoMap);
        filterChain.doFilter(parameterRequestWrapper, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

}
